-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sansa and XOR.c
82 lines (72 loc) · 2.13 KB
/
Sansa and XOR.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @Repository HackerRank Soulutions
* @file Sansa and XOR
* @author Abdelrahman Ahmed Moussa ([email protected])
* @copyright Copyright (c) 2024
*
*/
/*********************************************best one*****************************************************/
int sansaXor(int arr_count, int* arr)
{
// initialize result by 0 as (a XOR 0 = a)
int result = 0;
// if arr_count is even number, all numbers will appear even number of times. So result is 0.
if (arr_count % 2 == 0)
{
result=0;
}
//else
//then frequency of elements at even positions are odd and frequency of elements at odd positions are even
// notice that this is zero indexed array
for (int i = 0; i<arr_count; i+=2)
{
result ^= arr[i];
}
return result;
}
/***** resources
https://www.geeksforgeeks.org/xor-subarray-xors-set-2/?ref=ml_lbp
*****/
/***********************this code produce time limit exceed****************************/
/*
int sansaXor(int arr_count, int* arr)
{
int i,j,m;
int result=0;
//1^2^3^(1^2)^(2^3)^(1^2^3)>> because 1^2^3 repeated twice there is no need to loop on it because the result is always zero
// loop only for this (1^2)^(2^3)>>>> (first index^2^.....^last index-1)^(first index+1^3^......last index-1)
for (i=0; i<arr_count; i++)
{
for (m=1;m<arr_count-1;m++)
{
result=result^arr[i];
for (j=i+1; j<arr_count-m; j++)
{
result=result^arr[j];
}
}
}
return result;
}
*/
/***********************************************************************/
/*
int sansaXor(int arr_count, int* arr)
{
// initialize result by 0 as (a XOR 0 = a)
long result = 0;
long freq=0;
// loop over all elements once
for (int i = 0; i < arr_count; i++)
{
// get the frequency of current element
freq = (i + 1) * (arr_count - i);
// if frequency is odd, then XOR it with the result
if (freq % 2 == 1)
{
result = result ^ arr[i];
}
}
return result;
}
*/